using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace Ack
{
	class MainClass
	{		
		private static void WriteUsage()
		{
			Console.WriteLine("  Compress: Ack.exe [-h] <file>");
			Console.WriteLine("Decompress: Ack.exe -d <file>");
			Console.WriteLine();
			Console.WriteLine("   Options: -h   Enable Huffman-encoding.");
			Console.WriteLine("            -c   Allow palette remapping.");
		}
		
		public static void Main (string[] args)
		{
			if(args.Length < 1)
			{
				WriteUsage();
				return;
			}
			
			if(args[0] == "-test")
			{
				RunTest();
			}
			else if(args[0] == "-d")
			{
				if(args.Length != 2)
				{
					WriteUsage();
					return;
				}
				
				string path = args[1];
				if(!File.Exists(path))
				{
					Console.WriteLine("Can't find file!");
					return;
				}
				
				if(!path.EndsWith(".ack"))
				{
					Console.WriteLine("Not an ACK compressed file!");
					return;
				}

				string outPath = path.Substring(0,path.LastIndexOf('.'))+"_decompressed.chr";

				List<byte> compressed = new List<byte>();
			
				using(FileStream f = File.OpenRead(path))
				{
					byte[] buffer = new byte[f.Length];
					f.Read(buffer, 0, (int)f.Length);
					f.Close();
					compressed.AddRange(buffer);
				}
				
				List<byte> decompressed = DecompressFile(compressed);
				
				using(FileStream ff = File.Create(outPath))
				{
					ff.Write(decompressed.ToArray(),0,decompressed.Count);
					ff.Close();
				}				
				
			}
			else
			{
				bool enableHuffman = false;
				bool allowColorRemap = false;
				
				int pathPos = 0;
				while(pathPos < args.Length && args[pathPos].StartsWith("-"))
				{
					switch(args[pathPos])
					{
					case "-h": enableHuffman = true; break;
					case "-c": allowColorRemap = true; break;
					}
					
					pathPos++;
				}

				if(pathPos >= args.Length)
				{
					Console.WriteLine("No path found in argument list.");
					return;
				}
				
				string path = args[pathPos];
				
				if(!File.Exists(path))
				{
					Console.WriteLine("Can't find file!");
					return;
				}
				
				if(!path.EndsWith(".chr"))
				{
					Console.WriteLine("Not a CHR file!");
					return;
				}
				
				string outPath = path + ".ack";
				
				List<byte> original = new List<byte>();
				using(FileStream f = File.OpenRead(path))
				{
					byte[] buffer = new byte[f.Length];
					f.Read(buffer, 0, (int)f.Length);
					f.Close();
					original.AddRange(buffer);
				}			
				
				NesEncoderParameters parms = new NesEncoderParameters();
				parms.EnableHuffman = enableHuffman;
				parms.AllowColorRemap = allowColorRemap;
				List<byte> compressed = CompressFile(original,parms,null);
			
				using(FileStream ff = File.Create(outPath))
				{
					ff.Write(compressed.ToArray(),0,compressed.Count);
					ff.Close();
				}				
			}
		}
		
		private static List<byte> DecompressFile(List<byte> compressed)
		{
			List<byte> decompressed = new List<byte>();
			
			int cmpBlockCount = compressed[0];
				int cmpBlockStart = 1+cmpBlockCount*2;
				for(int i = 0; i < cmpBlockCount; ++i)
				{
					int cmpBlockLength = (compressed[i*2+2] << 8) | compressed[i*2+1];
				
				List<byte> block = null;
				
					if((cmpBlockLength & 0x8000)!=0)
					{
					    cmpBlockLength &= 0x7FFF;
					block = NesDecoder2.Decode(new HuffmanDecoder(compressed.GetRange(cmpBlockStart, cmpBlockLength)));
					}
				else
				{
					block = NesDecoder2.Decode(new DummySupplier(compressed.GetRange(cmpBlockStart, cmpBlockLength)));
				}
				
				decompressed.AddRange(block);
					
					cmpBlockStart += cmpBlockLength;
				}
			
			return decompressed;
		}
		
		private static List<byte> CompressFile(List<byte> original,NesEncoderParameters parms, NesEncoder2.Statistics encStats)
		{
			List<byte> compressed = new List<byte>();
			compressed.Add(0);

			if(encStats==null)
				encStats = new NesEncoder2.Statistics();
			
			int blockSize = 8192;
			for(int bytePos = 0; bytePos < original.Count; bytePos += blockSize)
			{
				int byteCount = Math.Min(original.Count-bytePos, blockSize);
				
				if(byteCount > 0)
				{
					NesEncoder2 enc = new NesEncoder2();
					List<byte> blk = original.GetRange(bytePos, byteCount);
					List<byte> nesData = enc.Encode(parms,blk.ToArray(),encStats);

					if(parms.EnableHuffman)
					{
						List<byte> nesNibbleData = new List<byte>();
						for(int i = 0; i < nesData.Count; ++i)
						{
							nesNibbleData.Add((byte)(nesData[i] & 0x0F));
							nesNibbleData.Add((byte)((nesData[i] >> 4) & 0x0F));
						}
						
						List<byte> compressedBlock = Huffman.Encode(nesNibbleData, 16);

						if(compressedBlock.Count > 0x7FFF)
							throw new Exception("Compressed block too big: " + compressedBlock.Count);
						
						compressed.InsertRange(1 + compressed[0]*2, BitConverter.GetBytes((ushort)(compressedBlock.Count|0x8000)));
						compressed[0]++;
						compressed.AddRange(compressedBlock);
					}
					else
					{
						if(nesData.Count > 0x7FFF)
							throw new Exception("Compressed block too big: " + nesData.Count);
						
						compressed.InsertRange(1 + compressed[0]*2, BitConverter.GetBytes((ushort)nesData.Count));
						compressed[0]++;
						compressed.AddRange(nesData);
					}
				}
			}
			
			//Console.WriteLine(encStats);
			
			return compressed;
		}

		private static void RunTest()
		{
			string[] files = new string[]
			{
				"/home/therese/Documents/NESdev Corpus/battlekid.chr",
				"/home/therese/Documents/NESdev Corpus/bombsweeper.chr",
				"/home/therese/Documents/NESdev Corpus/cmc80s.chr",
				"/home/therese/Documents/NESdev Corpus/dpadhero.chr",
				"/home/therese/Documents/NESdev Corpus/geminim.chr",
				"/home/therese/Documents/NESdev Corpus/gemventure.chr",
				"/home/therese/Documents/NESdev Corpus/lj65.chr",
				"/home/therese/Documents/NESdev Corpus/manhole.chr",
				"/home/therese/Documents/NESdev Corpus/neotoxin.chr",
				"/home/therese/Documents/NESdev Corpus/nesnake2.chr",
				"/home/therese/Documents/NESdev Corpus/quantdisco.chr",
				"/home/therese/Documents/NESdev Corpus/sackofflour.chr",
				"/home/therese/Documents/NESdev Corpus/solarwars.chr",
				"/home/therese/Documents/NESdev Corpus/sting.chr",
				"/home/therese/Documents/nesrom_corpus/smb.chr",/*
				"/home/therese/Documents/nesrom_corpus/smb3.chr",
				"/home/therese/Documents/nesrom_corpus/kirbysadventure.chr",
				"/home/therese/Documents/nesrom_corpus/zelda2.chr",
				"/home/therese/Documents/nesrom_corpus/sma4.chr",*/
			};

			NesEncoder2.Statistics encStats = new NesEncoder2.Statistics();
			
			foreach(string fname in files)
			{
				List<byte> original = new List<byte>();
				using(FileStream f = File.OpenRead(fname))
				{
					byte[] buffer = new byte[f.Length];
					f.Read(buffer, 0, (int)f.Length);
					f.Close();
					original.AddRange(buffer);
				}					
//				Console.WriteLine();
				
//				DateTime dt = DateTime.Now;
				NesEncoderParameters parms = new NesEncoderParameters();
				parms.EnableHuffman = false;
				parms.AllowColorRemap = true;
				List<byte> compressed = CompressFile(original,parms,encStats);
//				Console.WriteLine(compressed.Count + " in " + (DateTime.Now-dt).TotalMilliseconds + " ms");
//				Console.Out.Flush();
				Console.WriteLine(compressed.Count);
				
				List<byte> decompressed = DecompressFile(compressed);
				
				// Verify data
				
				if(original.Count != decompressed.Count)
				{
					throw new Exception("Failed: Bad total length for " + fname);
				}
				
				bool match = true;
				for(int t = 0; t < original.Count; ++t)
				{
					if(original[t] != decompressed[t])
					{
						match = false;
						break;
					}
				}
				
				if(!match)
				{
					throw new Exception("Failed: Bad data in " + fname);
				}
			}		
			Console.WriteLine(encStats);
/*
			foreach(KeyValuePair<int,int> kvp in encStats._countsPerOffset)
			{
				Console.WriteLine(kvp.Key + "," + kvp.Value);
			}			
*/		}
		
	}
}
